/**
 * 去除字符串中除了数字和点以外的其他字符
 * @param {Object} obj
 */
export const clearNoNum = (obj) => {
	//如果用户第一位输入的是小数点，则重置输入框内容
	if (obj.value != '' && obj.value.substr(0, 1) == '.') {
		obj.value = '';
	}
	obj.value = obj.value.replace(/^0*(0\.|[1-9])/, '$1'); //粘贴不生效
	obj.value = obj.value.replace(/[^\d.]/g, ''); //清除“数字”和“.”以外的字符
	obj.value = obj.value.replace(/\.{2,}/g, '.'); //只保留第一个. 清除多余的
	obj.value = obj.value
		.replace('.', '$#$')
		.replace(/\./g, '')
		.replace('$#$', '.');
	obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数
	if (obj.value.indexOf('.') < 0 && obj.value != '') {
		//以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
		if (obj.value.substr(0, 1) == '0' && obj.value.length == 2) {
			obj.value = obj.value.substr(1, obj.value.length);
		}
	}
	return obj.value;
}


/**
 * 获取url链接参数
 * @param {Object} url
 * @param {Object} name
 */
export const getQueryString = (url, name) => {
	var reg = new RegExp('(^|&|/?)' + name + '=([^&|/?]*)(&|/?|$)', 'i')
	var r = url.substr(1).match(reg)
	if (r != null) {
		return r[2]
	}
	return null;
}

/**
 * 批量上传图片
 */
export const uploadImgs = async (files, title) => {
	try {
		let arrs = []

		for (let item of files) {
			const res = await imgToBase64(item)
			arrs.push(uploadImg({
				base64: res
			}))
		}
		const res = await Promise.all(arrs)
		return Promise.resolve(res)
	} catch (e) {
		console.log(e);
		uni.showToast({
			icon: "error",
			title: e
		})
	}
}

/**
 * 本地图片转base64
 */
export const imgToBase64 = (url) => {
	return new Promise((resolve, reject) => {
		uni.getFileSystemManager().readFile({
			filePath: url,
			encoding: 'base64',
			success: res => {
				let base64 = 'data:image/jpeg;base64,' + res.data
				resolve(base64)
			},
			fail: (e) => {
				reject("图片转换失败")
			}
		});
	})
}

/**
 * 保留两位小数
 */
export const twoNum = (num) => {
	return (parseInt(num * 100) / 100).toFixed(2) == 'NaN' ? '0.00' : (parseInt(num * 100) / 100).toFixed(2)
}

/**
 * 隐藏手机号中间四位
 */
export const phoneHide = (phone) => {
	return phone && phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
}

/*
 * 在抽奖的活动中经常会用到这个算法，不同奖项的获取概率不同，要按概率去随机生成对应的奖品
 */
export function random(arr1, arr2) {
	var sum = 0,
		factor = 0,
		random = Math.random();

	for (var i = arr2.length - 1; i >= 0; i--) {
		sum += arr2[i]; // 统计概率总和
	};
	random *= sum; // 生成概率随机数
	for (var i = arr2.length - 1; i >= 0; i--) {
		factor += arr2[i];
		if (random <= factor) return arr1[i];
	};
	return null;
}

/**
 * 保留小数n位，不进行四舍五入
 * num你传递过来的数字,
 * decimal你保留的几位,默认保留小数后两位
 * isInt 是否保留0
 */
export function formatDecimal(num = 0, decimal = 2, isInt = false) {
	num = parseFloat(num)
	num = num.toFixed(3).toString();
	const index = num.indexOf(".");
	if (index !== -1) {
		num = num.substring(0, decimal + index + 1);
	} else {
		num = num.substring(0);
	}
	//截取后保留两位小数
	if (isInt) {
		return parseFloat(num);
	} else {
		return parseFloat(num).toFixed(decimal);
	}
}

/**
 * 获取用户位置信息
 * tips 是否提示用户打开引导
 * @return {Promise}
 */
export const getLoaction = (tips = false) => {
	return new Promise((resolve, reject) => {
		const location = uni.getStorageSync('location');
		const ctime = Date.parse(new Date());
		const flagTime = 10;

		if (location && ctime / 1000 - location.time < flagTime) {
			resolve({
				lng: location.lng,
				lat: location.lat,
			})
		} else {
			uni.authorize({
				scope: 'scope.userLocation',
				success: res => {
					uni.getLocation({
						type: 'gcj02',
						success: res => {
							const timestemp = Date.parse(new Date());
							uni.setStorageSync('location', {
								lng: res.longitude,
								lat: res.latitude,
								time: timestemp / 1000
							});

							resolve({
								lng: res.longitude,
								lat: res.latitude,
							})
						}
					});
				},
				fail: err => {
					if (tips) {
						return uni.showModal({
							title: '提示',
							content: '定位失败，请授权后使用！',
							confirmText: '授权',
							success: res => {
								if (res.confirm) {
									uni.openSetting({
										success: async res => {
											if (res.authSetting[
													'scope.userLocation'
												]) {
												resolve(getLoaction())
											} else {
												reject('定位失败')
											}
										},
										fail: err => {
											reject('定位失败')
										}
									});
								} else {
									reject('定位失败')
								}
							},
							fail: async err => {
								reject('定位失败')
							}
						});
					} else {
						reject('定位失败')
					}
				}
			});
		}
	})
}